package com.jinhua.admin.service.impl;

import com.jinhua.admin.dao.OrderDao;
import com.jinhua.admin.dao.ProductDao;
import com.jinhua.admin.entity.OrderPo;
import com.jinhua.admin.entity.ProductPo;
import com.jinhua.admin.service.ProductService;
import com.jinhua.admin.vo.ProductVo;
import com.jinhua.config.BeanCopierUtil;
import com.jinhua.config.PaginationRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 商品表的service层
 */

@Service
@Slf4j
public class ProductServiceImpl implements ProductService {
    private final long ERROR_LONG = 0L;
    private final int ERROR_INT = 0;
    @Autowired
    private ProductDao productDao;

    @Autowired
    private OrderDao orderDao;


    private Lock lock = new ReentrantLock(true);

    @Transactional
    @Override
    public void saveProduct(ProductVo productVo) {
        lock.lock();
//        if (!lock.tryLock()) {
//                return;
//        }
        log.info(Thread.currentThread().getName()+",拿到锁");
        try {
//            if (!lock.tryLock(1, 30, TimeUnit.MINUTES)) {
//                return;
//            }
//            if (!lock.tryLock()) {
//                return;
//            }
            System.out.println(Thread.currentThread().getName() + ":抢到锁，进入方法");
            ProductPo product = productDao.findProductById(123L);
            Integer productCount = product.getProductCount();
            System.out.println(Thread.currentThread().getName() + "当前库存：" + productCount);
            if (productCount > 0) {
                ProductPo build = ProductPo.builder()
                        .name(product.getName())
                        .productCount(productCount - 1)
                        .build();
                build.setId(product.getId());
                productDao.modProduct(build);

                OrderPo order = OrderPo.builder()
                        .userName(Thread.currentThread().getName())
                        .goodsName(product.getName() == null ? "默认" : product.getName())
                        .build();

                orderDao.saveOrderIfNotExist(order);

                System.out.println(Thread.currentThread().getName() + ":减少库存，创建订单完成");
            } else {
                System.out.println(Thread.currentThread().getName() + ":没有库存了   ");
            }
            log.info(Thread.currentThread().getName()+"释放锁");
            lock.unlock();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }finally {

        }
    }

    @Override
    public int delProductByIds(Long... ids) {
        if (ids == null || ids.length == 0) {
            log.warn("删除商品表,ids集合为空");
            return ERROR_INT;
        }
        log.warn("start删除Id集合={},商品表", Arrays.asList(ids));
        return productDao.delProductByIds(ids);
    }

    @Override
    public ProductVo findProductById(Long id) {
        if (id == null || id <= 0L) {
            log.warn("根据Id查找商品表,所传Id不符合规范");
            return new ProductVo();
        }
        log.info("start根据Id={}查找商品表", id);
        ProductPo productPo = productDao.findProductById(id);
        return productPo == null ? new ProductVo() : productPo.copyProductVo();
    }

    @Override
    public List<ProductVo> findProductByAll(PaginationRequest<ProductVo> request) {
        List<ProductVo> productVos = new ArrayList<>();
        if (request == null) {
            log.warn("根据条件查找商品表,参数不对");
            return productVos;
        }
        log.info("start根据条件查找商品表={}", request);
        List<ProductPo> productPos = productDao.findProductByAll(request.getQueryCriteria().copyProductPo(), request.getPageNum(), request.getPageSize());
        BeanCopierUtil.copy(productPos, productVos);
        return productVos;
    }
}
